package com.example.boot.security.handler;

import com.example.boot.pojo.result.Result;
import com.example.boot.security.entity.LoginResult;
import com.example.boot.security.entity.SecurityUser;
import com.example.boot.utils.JwtHelper;
import com.example.boot.utils.RedisService;
import com.example.boot.utils.ResponseUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:  认证成功处理器
 * @author: mhpy
 * @date 2022/8/7 9:40
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //响应编码
        response.setContentType("application/json;charset=utf-8");
//        当前登录用户信息
        SecurityUser userInfo =(SecurityUser) authentication.getPrincipal();
        String userToken = JwtHelper.getUserToken(userInfo.getId(),userInfo.getName());
        LoginResult loginResult = new LoginResult(userInfo.getId(),userInfo.getName(),userInfo.getAvatar(),userToken);
//        token 保存到redis
        redisService.set("token_"+userToken,userToken,1800L);

        ResponseUtil.out(response, Result.success().data("item",loginResult));
    }
}

